#include "Game.hpp"
#include "Tank.hpp"
#include <iostream>
#include <sstream>
#include <array>
#include <cstddef>  // for size_t

// 敌人生成点
std::array<sf::Vector2f, 3> SPAWN_POINTS;

sf::Vector2u Game::getDesiredWindowSize() {
    // 获取桌面模式
    sf::VideoMode desktop = sf::VideoMode::getDesktopMode();
    
    // 使用桌面分辨率的75%作为游戏窗口大小
    return sf::Vector2u(
        static_cast<unsigned int>(desktop.width * 0.75f),
        static_cast<unsigned int>(desktop.height * 0.75f)
    );
}

Game::Game()
    : mWindow(sf::VideoMode(getDesiredWindowSize().x, getDesiredWindowSize().y), "坦克大战")
    , mMap(getDesiredWindowSize())
{
    // 计算敌人生成点位置
    auto windowSize = getDesiredWindowSize();
    float margin = 100.f;  // 距离边界的边距
    float spawnY = 50.f;   // 生成点的Y坐标（距离顶部50像素）
    
    // 计算三个生成点的X坐标，使其均匀分布
    float availableWidth = windowSize.x - 2 * margin;  // 可用宽度（减去两边的边距）
    float spacing = availableWidth / 2;  // 生成点之间的间距
    
    // 设置三个生成点
    SPAWN_POINTS[0] = sf::Vector2f(margin, spawnY);                    // 左边生成点
    SPAWN_POINTS[1] = sf::Vector2f(margin + spacing, spawnY);          // 中间生成点
    SPAWN_POINTS[2] = sf::Vector2f(margin + spacing * 2, spawnY);      // 右边生成点
    
    // 加载字体
    if (!mFont.loadFromFile("/usr/share/fonts/liberation/LiberationSans-Regular.ttf")) {
        std::cerr << "Warning: Failed to load primary font, trying fallback..." << std::endl;
        if (!mFont.loadFromFile("/usr/share/fonts/dejavu/DejaVuSans.ttf")) {
            std::cerr << "Warning: Failed to load fallback font. Text may not display correctly." << std::endl;
        }
    }

    // 设置说明文本
    mInstructionsText.setFont(mFont);
    mInstructionsText.setCharacterSize(16);
    mInstructionsText.setFillColor(sf::Color::White);
    mInstructionsText.setPosition(10, 10);
    mInstructionsText.setString(
        "Controls:\n"
        "W/S - Move Forward/Backward\n"
        "A/D - Rotate Left/Right\n"
        "Space - Shoot\n"
        "R - Restart when game over"
    );

    // 设置分数文本
    mScoreText.setFont(mFont);
    mScoreText.setCharacterSize(24);
    mScoreText.setFillColor(sf::Color::Yellow);
    mScoreText.setPosition(10, 550);
    
    // 设置游戏结束文本
    mGameOverText.setFont(mFont);
    mGameOverText.setCharacterSize(48);
    mGameOverText.setFillColor(sf::Color::Red);
    mGameOverText.setString("GAME OVER\nPress R to restart");
    mGameOverText.setPosition(250, 250);

    reset();
    loadAudio();
}

void Game::loadAudio() {
    // 加载背景音乐
    if (!mBackgroundMusic.openFromFile("resources/audio/background.wav")) {
        std::cerr << "Warning: Failed to load background music" << std::endl;
    } else {
        mBackgroundMusic.setLoop(true);  // 循环播放
        mBackgroundMusic.setVolume(50.f);  // 设置音量
        mBackgroundMusic.play();
    }

    // 加载转向音效
    if (!mTurnSoundBuffer.loadFromFile("resources/audio/turn.wav")) {
        std::cerr << "Warning: Failed to load turn sound" << std::endl;
    } else {
        mTurnSound.setBuffer(mTurnSoundBuffer);
        mTurnSound.setVolume(60.f);
    }
    
    // 设置窗口帧率
    mWindow.setFramerateLimit(60);
}

void Game::reset() {
    // 创建玩家坦克
    mPlayer = std::make_unique<Tank>(Tank::Type::Player, sf::Vector2f(400.f, 500.f), *this);
    
    // 清空敌人
    mEnemies.clear();
    
    // 加载默认地图
    mMap.loadDefaultMap();
    
    // 重置分数和游戏状态
    mScore = 0;
    mGameOver = false;
    
    // 重置生成计时器
    mSpawnClock.restart();
}

void Game::playTurnSound() {
    mTurnSound.play();
}

void Game::run() {
    sf::Clock clock;
    
    while (mWindow.isOpen()) {
        processEvents();
        
        sf::Time deltaTime = clock.restart();
        update(deltaTime);
        
        render();
    }
}

void Game::processEvents() {
    sf::Event event;
    while (mWindow.pollEvent(event)) {
        if (event.type == sf::Event::Closed) {
            mWindow.close();
        }
        
        // 键盘按下事件
        if (event.type == sf::Event::KeyPressed) {
            switch (event.key.code) {
                case sf::Keyboard::W:
                    mIsMovingUp = true;
                    break;
                case sf::Keyboard::S:
                    mIsMovingDown = true;
                    break;
                case sf::Keyboard::A:
                    mIsMovingLeft = true;
                    break;
                case sf::Keyboard::D:
                    mIsMovingRight = true;
                    break;
                case sf::Keyboard::Space:
                    mIsShooting = true;
                    break;
                case sf::Keyboard::R:
                    if (mGameOver) {
                        reset();
                    }
                    break;
                default:
                    break;
            }
        }
        
        // 键盘释放事件
        if (event.type == sf::Event::KeyReleased) {
            switch (event.key.code) {
                case sf::Keyboard::W:
                    mIsMovingUp = false;
                    break;
                case sf::Keyboard::S:
                    mIsMovingDown = false;
                    break;
                case sf::Keyboard::A:
                    mIsMovingLeft = false;
                    break;
                case sf::Keyboard::D:
                    mIsMovingRight = false;
                    break;
                case sf::Keyboard::Space:
                    mIsShooting = false;
                    break;
                default:
                    break;
            }
        }
    }
}

void Game::update(sf::Time deltaTime) {
    if (!mGameOver) {
        // 更新玩家坦克
        mPlayer->handleInput(mIsMovingUp, mIsMovingDown,
                           mIsMovingLeft, mIsMovingRight,
                           mIsShooting);
        mPlayer->update(deltaTime);
        
        // 生成敌人
        if (mSpawnClock.getElapsedTime().asSeconds() >= SPAWN_INTERVAL) {
            spawnEnemy();
            mSpawnClock.restart();
        }
        
        // 更新敌人
        for (auto it = mEnemies.begin(); it != mEnemies.end();) {
            // 更新敌人的玩家位置信息
            (*it)->setPlayerPosition(mPlayer->getPosition());
            (*it)->update(deltaTime);
            
            // 检查敌人是否死亡
            if ((*it)->getHealth() <= 0) {
                mScore += POINTS_PER_KILL;  // 增加得分
                it = mEnemies.erase(it);
            } else {
                ++it;
            }
        }
        
        // 处理碰撞
        handleCollisions();
        
        // 检查游戏是否结束
        checkGameOver();
    }
    
    // 无论游戏是否结束都更新分数显示
    std::stringstream ss;
    ss << "Score: " << mScore;
    mScoreText.setString(ss.str());
}

void Game::render() {
    mWindow.clear(sf::Color(0, 0, 0));
    
    // 渲染地图
    mMap.render(mWindow);
    
    // 渲染玩家
    mPlayer->render(mWindow);
    
    // 渲染敌人
    for (const auto& enemy : mEnemies) {
        enemy->render(mWindow);
    }
    
    // 渲染说明
    renderInstructions();
    
    // 渲染游戏状态
    renderGameStatus();
    
    mWindow.display();
}

void Game::handleCollisions() {
    // 检查坦克与地图的碰撞
    if (mMap.checkCollision(mPlayer->getBounds())) {
        mPlayer->undoLastMove();
    }
    
    for (auto& enemy : mEnemies) {
        if (mMap.checkCollision(enemy->getBounds())) {
            enemy->undoLastMove();
        }
    }
    
    // 检查子弹与墙体的碰撞
    for (auto& enemy : mEnemies) {
        // 检查敌人子弹
        enemy->checkBulletCollisions(mMap);
        
        // 检查敌人子弹是否击中玩家
        if (enemy->checkBulletCollisions(*mPlayer)) {
            mPlayer->damage(34);  // 玩家受到34点伤害（3次击中会死亡）
            mMap.playHitSound();
            if (mPlayer->getHealth() <= 0) {
                mGameOver = true;  // 立即设置游戏结束状态
            }
        }
    }
    
    // 检查玩家子弹与地图的碰撞
    mPlayer->checkBulletCollisions(mMap);
    
    // 检查玩家子弹是否击中敌人
    for (auto& enemy : mEnemies) {
        if (mPlayer->checkBulletCollisions(*enemy)) {
            enemy->damage(34);  // 敌人受到34点伤害（3次击中会死亡）
            mMap.playHitSound();  // 子弹命中时播放击中音效
            if (enemy->getHealth() <= 0) {
                mScore += POINTS_PER_KILL;
            }
        }
    }

    // 检查敌人子弹与玩家子弹的碰撞
    for (auto& enemy : mEnemies) {
        enemy->checkBulletCollisionsWithBullets(*mPlayer);
    }
    
    // 检查坦克之间的碰撞
    for (auto& enemy : mEnemies) {
        if (enemy->getBounds().intersects(mPlayer->getBounds())) {
            // 只让敌人坦克回退，让玩家保持控制
            enemy->undoLastMove();
        }
        
        // 检查敌人之间的碰撞
        for (auto& otherEnemy : mEnemies) {
            if (enemy != otherEnemy &&
                enemy->getBounds().intersects(otherEnemy->getBounds())) {
                // 只让一个敌人回退，避免死锁
                enemy->undoLastMove();
            }
        }
    }
}

void Game::spawnEnemy() {
    // 检查所有生成点
    std::vector<int> availableSpawnPoints;
    
    for (std::size_t i = 0; i < SPAWN_POINTS.size(); ++i) {
        bool isSpawnPointOccupied = false;
        sf::FloatRect spawnArea(
            SPAWN_POINTS[i].x - 32.f,  // 生成区域左上角X
            SPAWN_POINTS[i].y - 32.f,  // 生成区域左上角Y
            64.f,                      // 生成区域宽度
            64.f                       // 生成区域高度
        );
        
        // 检查是否有敌人坦克占据这个生成点
        for (const auto& enemy : mEnemies) {
            if (enemy->getBounds().intersects(spawnArea)) {
                isSpawnPointOccupied = true;
                break;
            }
        }
        
        // 如果生成点没有被占据，添加到可用生成点列表
        if (!isSpawnPointOccupied) {
            availableSpawnPoints.push_back(i);
        }
    }
    
    // 如果有可用的生成点，随机选择一个生成敌人
    if (!availableSpawnPoints.empty()) {
        int randomIndex = rand() % availableSpawnPoints.size();
        int spawnIndex = availableSpawnPoints[randomIndex];
        
        mEnemies.push_back(std::make_unique<Tank>(
            Tank::Type::Enemy,
            SPAWN_POINTS[spawnIndex],
            *this
        ));
    }
}

void Game::renderInstructions() {
    mWindow.draw(mInstructionsText);
}

void Game::renderGameStatus() {
    mWindow.draw(mScoreText);
    
    if (mGameOver) {
        mWindow.draw(mGameOverText);
    }
}

void Game::checkGameOver() {
    if (mPlayer->getHealth() <= 0) {
        if (!mGameOver) {
            mGameOver = true;
        }
    }
}